//
//  KKHellp.swift
//  JGTProject
//
//  Created by ifly on 2017/7/18.
//  Copyright © 2017年 szy. All rights reserved.
//



import Cocoa


class KKHellp: NSObject{


    ///  存储数据
    class func setObject(_ object:AnyObject ,forKey key:String) -> Void {
    
        let encodedObjec: NSData = NSKeyedArchiver.archivedData(withRootObject: object) as NSData
        let fileManager = FileManager.default
        let fileName:NSString = self.cacheDirectory().appendingPathComponent(key) as NSString
    
        if !fileManager.fileExists(atPath: self.cacheDirectory() as String) {
            do {
                try fileManager.createDirectory(atPath: self.cacheDirectory() as String, withIntermediateDirectories: true, attributes: nil)
            } catch  {
                print("创建文件失败")
            }
        }
        do {
            try encodedObjec.write(toFile: fileName as String, options: .atomic)
        } catch  {
            print("写入失败")

        }
    
    }
    ///   取数据
    class func object(forKey key:String) -> AnyObject {
        
        let fileManager = FileManager.default
        let fileName:NSString = self.cacheDirectory().appendingPathComponent(key) as NSString
        if fileManager.fileExists(atPath: self.cacheDirectory() as String) {
            
            let data = NSData(contentsOfFile: fileName as String)
            let object = NSKeyedUnarchiver.unarchiveObject(with: data! as Data)
            return object as AnyObject
        }
        return "" as AnyObject
    }
    ///   删除所有
    class  func deleteCaches() -> Void {
        do {
            try FileManager.default.removeItem(atPath: self.cacheDirectory() as String)
        } catch  {
            
        }
    }
    ///   根据关键字删除
    class func deleteCache(forKey key:String){
        
        let newCacheDirectory =  self.cacheDirectory().appendingPathComponent(key)
        do {
            try FileManager.default.removeItem(atPath: newCacheDirectory as String)
        } catch  {
            
        }
    }
    
    private class func cacheDirectory() -> NSString {
        
        // 获取目录方式1
        let paths:NSArray = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true) as NSArray
        let cacheDirectory = paths.object(at: 0) as! NSString
        let newCacheDirectory =  cacheDirectory.appendingPathComponent("KKCACHES")
// 获取目录方式2
//        let cacheDirectory:NSString = NSHomeDirectory() + "/Library/Caches/kk_Caches" as NSString //
//        print("创建的目录\(newCacheDirectory)")

        return newCacheDirectory as NSString
    }
    
}





